package models;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
import com.amazonaws.services.dynamodbv2.util.Tables;

import entities.Domain;

public class ADDB_DomainModel {
	private static ADDB_DomainModel instance = null;
	
	private static AmazonDynamoDB dynamoDB = null;
	
	private static DynamoDBMapper mapper = null;
	
	private static String tableName = "builtwith_domain";
	
	private static String tableKeyName = "name";
	
	public static ADDB_DomainModel getInstance() {
		if (instance == null) {
			instance = new ADDB_DomainModel();
		}
		
		return instance;
	}
	
	private ADDB_DomainModel() {
		dynamoDB = new AmazonDynamoDBClient(new ClasspathPropertiesFileCredentialsProvider());
		Region region = Region.getRegion(Regions.US_EAST_1);
		dynamoDB.setRegion(region); 
		mapper = new DynamoDBMapper(dynamoDB);
		
		//Create table
		if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName(tableKeyName).withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName(tableKeyName).withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
                TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest).getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, tableName);
        }
	}
	
	public static void insert(Domain domain) {
		mapper.save(domain);
	}
	
	public static void delete(Domain domain) {
		mapper.delete(domain);
	}
}